﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Kgb.Model.Models;
using Kgb.Service.Repository.Interface;
using System.Runtime.Caching;

namespace Kgb.Service.Repository
{
    public class RoomRepository : IRoomRepository
    {
        private List<Room> _rooms;
        private int _nextId;

        public RoomRepository()
        {
            if (MemoryCache.Default["rooms"] == null)
            {
                _rooms = new List<Room>();
                MemoryCache.Default.Add(new CacheItem("rooms", _rooms), new CacheItemPolicy() { AbsoluteExpiration = new DateTime(9999, 12, 31) });
            }
            else
            {
                _rooms = (List<Room>)MemoryCache.Default["rooms"];
            }


            if (_rooms.Any())
            {
                _nextId = _rooms.Max(c => c.Id) + 1;
            }
            else
            {
                _nextId = 1;

                //inicializa repositório de entradas
                LobbyRepository _lobbies = new LobbyRepository();

                foreach(Lobby lobby in _lobbies.GetAll())
                {
                    for (int i = 1; i <= 4; i++)
                    {
                        this.Add(new Room() { Name = "Sala " + i.ToString(), State = "Vazia", LobbyId = lobby.Id });
                    } 
                }
            }
        }

        public IQueryable<Room> GetAll()
        {
            return _rooms.AsQueryable();
        }

        public IQueryable<Room> GetAllByLobby(int lobbyId)
        {
            return _rooms.Where(r => r.LobbyId == lobbyId).AsQueryable();
        }

        public Room Get(int id)
        {
            return _rooms.Find(c => c.Id == id);
        }

        public Room Add(Room room)
        {
            room.Id = _nextId++;
            _rooms.Add(room);
            return room;
        }

        public void Remove(int id)
        {
            Room room = _rooms.Find(c => c.Id == id);
            if (room != null)
                _rooms.Remove(room);
        }

        public bool Update(Room room)
        {
            int index = _rooms.FindIndex(c => c.Id == room.Id);
            if (index == -1)
            {
                return false;
            }
            _rooms.RemoveAt(index);
            _rooms.Add(room);
            return true;
        }

    }
}